import sys

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException
from fastapi import status

from cacheout import Cache

from jose import JWTError, jwt
from models import User
from .config import settings

global_user_cache = Cache(maxsize=sys.maxsize,ttl=900)

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/login")

# oauth2_scheme 请求头中取到 Authorization的value
async def get_current_user(token: str = Depends(oauth2_scheme)) -> User:
    """
    解析token 获取当前用户
    """
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        username: str = payload.get("sub",None)
        if username is None:
            raise credentials_exception
    except JWTError:
        raise credentials_exception
    user = await User.get(username=username)
    if user is None:
        raise credentials_exception
    
    ## 记录登录信息
    global global_user_cache
    global_user_cache.set(user.username,token)
    
    return user

async def logout(user: User = Depends(get_current_user)):
    global global_user_cache
    global_user_cache.delete(user.username)
    return